<?php
/*
Plugin Name: VTP partners
Plugin URI: http://www.dudyland.sk
Description: VTP partners
Version: 0.1
Author: Peter Turza, Pavol Martiniak
Author URI: http://www.dudyland.sk
*/
?>
<?php
class VTPPartners {

    private $wpdb;
    private static $maxActivityLength = 10000; // obmedzenie dlzky textu
    
    function  __construct() {
        global $wpdb;
        $this->wpdb = $wpdb;
        add_action('admin_menu', array(&$this, 'partnersMenu'));
        wp_register_script('jquery-validate', get_bloginfo(url).'/wp-includes/js/validate/jquery.validate.js');
        wp_register_script('myscript', get_bloginfo(url).'/wp-includes/js/validate/myscript.js');

        // YUI editor
        wp_register_style('yui-skin-sam', '/wp-includes/js/yui/build/assets/skins/sam/skin.css');
        wp_register_script('yahoo-dom-event', get_bloginfo(url).'/wp-includes/js/yui/build/yahoo-dom-event/yahoo-dom-event.js'); 
        wp_register_script('element', get_bloginfo(url).'/wp-includes/js/yui/build/element/element-min.js'); 
        wp_register_script('container_core', get_bloginfo(url).'/wp-includes/js/yui/build/container/container_core-min.js'); 
        wp_register_script('menu', get_bloginfo(url).'/wp-includes/js/yui/build/menu/menu-min.js'); 
        wp_register_script('button', get_bloginfo(url).'/wp-includes/js/yui/build/button/button-min.js'); 
        wp_register_script('editor1', get_bloginfo(url).'/wp-includes/js/yui/build/editor/editor-min.js'); 
    }

    function partnersMenu() {
        add_menu_page('VTP Partners', 'Partneri', 'edit_pages', 'partnersMenu', array(&$this, 'listAll'));
        add_submenu_page('partnersMenu', 'Pridať nového partnera', 'Pridať nového partnera', 'edit_pages', 'addPartner', array(&$this, 'addPartner'));
        wp_enqueue_script('jquery-validate');
        wp_enqueue_script('myscript');
        
        wp_enqueue_style('yui-skin-sam');
        wp_enqueue_script('yahoo-dom-event');
        wp_enqueue_script('element');
        wp_enqueue_script('container_core');
        wp_enqueue_script('menu');
        wp_enqueue_script('button');        
        wp_enqueue_script('editor1');
    }

    /**
    * @desc Funkcia sluzi ako navigacia medzi jednotlivymi metodami.
    */
    function listAll() {
        if ($_GET['action'] == 'edit') { // editacia
            $this->editPartner($_GET['id']);
        } else if ($_GET['action'] == 'delete') { // mazanie
            $this->deletePartner($_GET['id']);
        } else { // listing
            $this->listing();
        }
    }
    
    /**
    * @desc Zobrazi formular a pridava zaznam do DB.
    */
    function addPartner() {
        if (!isset($_POST['submitted'])) { // show form
            echo VTPPartners::initYuiEditor();
            
            echo '<div id="wrap">';
            echo '<h2>Pridať nového partnera</h2>';
            
            echo '<form action="'.$_SERVER['REQUEST_URI'].'" id="addPartner" method="post" enctype="multipart/form-data">';
            echo '<table class="form-table">';
            echo '<tr><td><label for="partnerName">Názov partnera: *</label></td>';
            echo '<td><input type="text" name="partnerName" id="partnerName" value="" /></td></tr>';
            echo '<tr><td><label for="partnerLogo">Logo partnera: *</label></td>';
            echo '<td><input type="file" name="partnerLogo" id="partnerLogo" /></td></tr>';
            echo '<tr><td><label for="partnerCategory">Kategória: *</label></td><td>';
            wp_dropdown_categories(array('child_of'=>4, 'hide_empty'=>0, 'name'=>'partnerCategory'));
            echo '</td></tr>';
            echo '<tr><td><label for="partnerActivity">Popis činnosti: </label></td>';
            echo '<td><textarea name="partnerActivity" id="partnerActivity" ></textarea></td></tr>';            
            echo '<tr><td><label for="partnerEmail">Kontaktný email: *</label></td>';
            echo '<td><input type="text" name="partnerEmail" id="partnerEmail" value="" /></td></tr>';
            echo '<tr><td><label for="partnerPhone1">Telefón 1: </label></td>';
            echo '<td><input type="text" name="partnerPhone1" value="" /></td></tr>';
            echo '<tr><td><label for="partnerPhone2">Telefón 2: </label></td>';
            echo '<td><input type="text" name="partnerPhone2" value="" /></td></tr>';                        
            echo '<tr><td><label for="partnerPhone1">Telefón 3: </label></td>';
            echo '<td><input type="text" name="partnerPhone3" value="" /></td></tr>';
            echo '<tr><td><label for="partnerFax">Fax: </label></td>';
            echo '<td><input type="text" name="partnerFax" value="" /></td></tr>';
            echo '<tr><td><label for="partnerWeb">Web: </label></td>';
            echo '<td><input type="text" name="partnerWeb" value="" /></td></tr>';
            echo '<tr><td><label for="partnerIcq">Icq: </label></td>';
            echo '<td><input type="text" name="partnerIcq" value="" /></td></tr>';
            echo '<tr><td><label for="partnerSkype">Skype: </label></td>';
            echo '<td><input type="text" name="partnerSkype" value="" /></td></tr>';
            echo '<tr><td><label for="partnerGtalk">Gtalk: </label></td>';
            echo '<td><input type="text" name="partnerGtalk" value="" /></td></tr>';
            echo '<tr><td><label for="partnerJabber">Jabber: </label></td>';
            echo '<td><input type="text" name="partnerJabber" value="" /></td></tr>';
            echo '<tr><td><label for="partnerMsn">Msn: </label></td>';
            echo '<td><input type="text" name="partnerMsn" value="" /></td></tr>';
            
            echo '<input type="hidden" name="submitted" value="true">';
            
            echo '<tr><td></td><td><input type="submit" id="submit" value="Pridať partnera" /></td></tr>';
            echo '</table>';
            echo '</form>';
            echo '<script type="text/javascript">
                    jQuery("#addPartner").validate({
                        rules: {
                            partnerName: {required: true},
                            partnerLogo: {required: true, accept: "jpe?g|gif|png"},
                            partnerActivity: {maxlength : '.VTPPartners::$maxActivityLength.'},
                            partnerEmail: {required: true, email: true},
                            partnerPhone1: {},
                            partnerPhone2: {},
                            partnerPhone3: {},
                            partnerFax: {},
                            partnerWeb: {url: true}
                        }
                    });
                    
                    jQuery("#addPartner").submit(function() {
                        myEditor.saveHTML();
                    });                    
                    </script>';
            echo '</div>';
        } else {
            // insertion
            $name = $_POST['partnerName'];
            $logo = $_FILES['partnerLogo']['name'];
            $category = $_POST['partnerCategory'];
            $activity = $_POST['partnerActivity'];
            $email = $_POST['partnerEmail'];
            $phone1 = $_POST['partnerPhone1'];
            $phone2 = $_POST['partnerPhone2'];
            $phone3 = $_POST['partnerPhone3'];
            $fax = $_POST['partnerFax'];
            $web = $_POST['partnerWeb'];
            $icq = $_POST['partnerIcq'];
            $skype = $_POST['partnerSkype'];
            $gtalk = $_POST['partnerGtalk'];
            $jabber = $_POST['partnerJabber'];
            $msn = $_POST['partnerMsn'];
            
            // kontrola, ci uz je zaznam v DB - kvoli duplicite pri refreshnuti po vlozeni
            $checkRow = $this->wpdb->get_row("SELECT * FROM wp_partners WHERE name='$name' AND logo='$logo' AND category=$category
            AND email='$email' AND phone1='$phone1' AND phone2='$phone2' AND phone3='$phone3' AND fax='$fax' AND web='$web'
            AND icq='$icq' AND skype='$skype' AND gtalk='$gtalk' AND jabber='$jabber' AND msn='$msn'");
            
            if ($checkRow == null) {
                // Create post object
                $partnerPost = array();
                $partnerPost['post_title'] = $name;
                $partnerPost['post_content'] = str_replace("\n"," ",str_replace("\r"," ",$activity));
                $partnerPost['post_status'] = 'publish';
                $partnerPost['post_category'] = array($category);

                // Insert the post into the database
                $postId = wp_insert_post( $partnerPost );

                update_post_meta($postId, 'partner', 1);
                update_post_meta($postId, 'email', $email);
                update_post_meta($postId, 'phone1', $phone1);
                update_post_meta($postId, 'phone2', $phone2);
                update_post_meta($postId, 'phone3', $phone3);
                update_post_meta($postId, 'fax', $fax);
                update_post_meta($postId, 'web', $web);
                update_post_meta($postId, 'icq', $icq);
                update_post_meta($postId, 'skype', $skype);
                update_post_meta($postId, 'gtalk', $gtalk);
                update_post_meta($postId, 'jabber', $jabber);
                update_post_meta($postId, 'msn', $msn);
                
                $data = array('id' => 'NULL', 'name' => $name, 'logo' => $logo, 'category' => $category,
                    'activity' => $activity, 'email' => $email, 'phone1' => $phone1, 'phone2' => $phone2, 
                    'phone3' => $phone3, 'fax' => $fax, 'web' => $web, 'icq' => $icq, 'skype' => $skype, 
                    'gtalk' => $gtalk, 'jabber' => $jabber, 'msn' => $msn, 'post_id'=>$postId);
                    
                // vloz do DB
                $this->wpdb->insert('wp_partners', $data);
                $lastId = $this->wpdb->insert_id;
                
                // presun foto do upload priecinku
                
                $upload = VTPPartners::my_wp_upload_bits($_FILES["partnerLogo"]["name"], null, file_get_contents($_FILES["partnerLogo"]["tmp_name"]), null, '/partners/'.$lastId );
                
                // pridaj fotku do galerie postu
                $attachment = array(
                    'post_title'=>$_FILES["partnerLogo"]["name"],
                    'post_content'=>'',
                    'post_status' => 'publish',
                    'post_mime_type'=>$_FILES["partnerLogo"]['type']);
                $filename = $upload['file'];
                $attachId = wp_insert_attachment( $attachment, $filename, $postId );
                $attachData = wp_generate_attachment_metadata( $attachId, $filename );
                wp_update_attachment_metadata( $attachId,  $attachData );
                update_post_meta($postId, 'logo', $attachId);
            }
            
            unset($_POST['submitted']);
            unset($_GET['action']);
            $this->listAll();            
        }
    }
    
    /**
    * @desc Formular na editaciu zaznamov.
    */
    private function editPartner($id) {
        if (!isset($_POST['submitted'])) { // show form
            $partner = $this->wpdb->get_row('SELECT * FROM wp_partners WHERE id = '.$id);
            echo VTPPartners::initYuiEditor();
            
            echo '<div id="wrap">';
            echo '<h2>Upraviť partnera "'.$partner->name.'"</h2>';
            
            echo '<form action="'.$_SERVER['REQUEST_URI'].'" id="editPartner" method="post" enctype="multipart/form-data">';
            echo '<table class="form-table">';
            echo '<tr><td><label for="partnerName">Názov partnera: *</label>';
            echo '<td><input type="text" name="partnerName" id="partnerName" value="'.$partner->name.'" /></td></tr>';
            jr_post_image($partner->post_id);
            echo '<tr><td><label for="partnerLogo">Logo partnera: *</label></td>';
            echo '<td><input type="file" name="partnerLogo" id="partnerLogo" /></td></tr>';
            echo '<tr><td><label for="partnerCategory">Kategória: *</label></td><td>';
            wp_dropdown_categories(array('child_of'=>4, 'hide_empty'=>0, 'name'=>'partnerCategory', 'selected'=>$partner->category));
            echo '</td></tr>';
            echo '<tr><td><label for="partnerActivity">Popis činnosti: </label></td>';
            echo '<td><textarea name="partnerActivity" id="partnerActivity" >'.$partner->activity.'</textarea></td></tr>';
            echo '<tr><td><label for="partnerEmail">Kontaktný email: *</label></td>';
            echo '<td><input type="text" name="partnerEmail" id="partnerEmail" value="'.$partner->email.'" /></td></tr>';
            echo '<tr><td><label for="partnerPhone1">Telefón 1: </label></td>';
            echo '<td><input type="text" name="partnerPhone1" value="'.$partner->phone1.'" /></td></tr>';
            echo '<tr><td><label for="partnerPhone2">Telefón 2: </label></td>';
            echo '<td><input type="text" name="partnerPhone2" value="'.$partner->phone2.'" /></td></tr>';                        
            echo '<tr><td><label for="partnerPhone1">Telefón 3: </label></td>';
            echo '<td><input type="text" name="partnerPhone3" value="'.$partner->phone3.'" /></td></tr>';
            echo '<tr><td><label for="partnerFax">Fax: </label></td>';
            echo '<td><input type="text" name="partnerFax" value="'.$partner->fax.'" /></td></tr>';
            echo '<tr><td><label for="partnerWeb">Web: </label></td>';
            echo '<td><input type="text" name="partnerWeb" value="'.$partner->web.'" /></td></tr>';
            echo '<tr><td><label for="partnerIcq">Icq: </label></td>';
            echo '<td><input type="text" name="partnerIcq" value="'.$partner->icq.'" /></td></tr>';
            echo '<tr><td><label for="partnerSkype">Skype: </label></td>';
            echo '<td><input type="text" name="partnerSkype" value="'.$partner->skype.'" /></td></tr>';
            echo '<tr><td><label for="partnerGtalk">Gtalk: </label></td>';
            echo '<td><input type="text" name="partnerGtalk" value="'.$partner->gtalk.'" /></td></tr>';
            echo '<tr><td><label for="partnerJabber">Jabber: </label></td>';
            echo '<td><input type="text" name="partnerJabber" value="'.$partner->jabber.'" /></td></tr>';
            echo '<tr><td><label for="partnerMsn">Msn: </label></td>';
            echo '<td><input type="text" name="partnerMsn" value="'.$partner->msn.'" /></td></tr>';

            echo '<input type="hidden" name="postId" value="'.$partner->post_id.'">';
            echo '<input type="hidden" name="submitted" value="true">';
            
            echo '<tr><td></td><td><input type="submit" value="Upraviť partnera" /></td></tr>';
            echo '</table>';
            echo '</form>';
            echo '<script type="text/javascript">
                    jQuery("#editPartner").validate({
                        rules: {
                            partnerName: {required: true},
                            partnerLogo: {accept: "jpe?g|gif|png"},
                            partnerActivity: {maxlength : '.VTPPartners::$maxActivityLength.'},
                            partnerEmail: {required: true, email: true},
                            partnerPhone1: {},
                            partnerPhone2: {},
                            partnerPhone3: {},
                            partnerFax: {},
                            partnerWeb: {url: true}
                        }
                    });
                    
                    jQuery("#editPartner").submit(function() {
                        myEditor.saveHTML();
                    });                    
                    </script>';
            echo '</div>';
            
        } else {
            $name = $_POST['partnerName'];
            $logo = $_FILES['partnerLogo']['name'];
            $category = $_POST['partnerCategory'];
            $activity = $_POST['partnerActivity'];
            $email = $_POST['partnerEmail'];
            $phone1 = $_POST['partnerPhone1'];
            $phone2 = $_POST['partnerPhone2'];
            $phone3 = $_POST['partnerPhone3'];
            $fax = $_POST['partnerFax'];
            $web = $_POST['partnerWeb'];
            $icq = $_POST['partnerIcq'];
            $skype = $_POST['partnerSkype'];
            $gtalk = $_POST['partnerGtalk'];
            $jabber = $_POST['partnerJabber'];
            $msn = $_POST['partnerMsn'];
            
            // Create post object
            $partnerPost = array();
            $partnerPost['ID'] = $_POST['postId'];
            $partnerPost['post_title'] = $name;
            $partnerPost['post_content'] = str_replace("\n"," ",str_replace("\r"," ",$activity));
            $partnerPost['post_status'] = 'publish';
            $partnerPost['post_category'] = array($category);

            // Insert the post into the database
            $postId = wp_update_post( $partnerPost );

            update_post_meta($postId, 'partner', 1);
            update_post_meta($postId, 'email', $email);
            update_post_meta($postId, 'phone1', $phone1);
            update_post_meta($postId, 'phone2', $phone2);
            update_post_meta($postId, 'phone3', $phone3);
            update_post_meta($postId, 'fax', $fax);
            update_post_meta($postId, 'web', $web);
            update_post_meta($postId, 'icq', $icq);
            update_post_meta($postId, 'skype', $skype);
            update_post_meta($postId, 'gtalk', $gtalk);
            update_post_meta($postId, 'jabber', $jabber);
            update_post_meta($postId, 'msn', $msn);


            $data = array('name' => $name, 'category' => $category,
                'activity' => $activity, 'email' => $email, 'phone1' => $phone1, 'phone2' => $phone2, 
                'phone3' => $phone3, 'fax' => $fax, 'web' => $web, 'icq' => $icq, 'skype' => $skype, 
                'gtalk' => $gtalk, 'jabber' => $jabber, 'msn' => $msn, 'post_id'=>$postId);
                            
            if ($logo != '') { // ak bola zmenena fotka
                $data['logo'] = $logo;
            }
                
            // vloz do DB
            $this->wpdb->update('wp_partners', $data, array( 'id' => $id ));
            
            // presun foto do upload priecinku, ak bola zmenena fotka
            if ($logo != '') {
                wp_delete_attachment(get_post_meta($postId, 'logo', true));
                $upload = VTPPartners::my_wp_upload_bits($_FILES["partnerLogo"]["name"], null, file_get_contents($_FILES["partnerLogo"]["tmp_name"]), null, '/partners/'.$id );
                $attachment = array(
                    'post_title'=>$_FILES["partnerLogo"]["name"],
                    'post_content'=>'',
                    'post_status' => 'publish',
                    'post_mime_type'=>$_FILES["partnerLogo"]['type']);
                $filename = $upload['file'];
                $attachId = wp_insert_attachment( $attachment, $filename, $postId );
                $attachData = wp_generate_attachment_metadata( $attachId, $filename );
                wp_update_attachment_metadata( $attachId,  $attachData );
                update_post_meta($postId, 'logo', $attachId);
            }
                        
            unset($_POST['submitted']);
            unset($_GET['action']);
            $this->listAll();
        }
    }
    
    /**
    * @desc Zmaze zaznam a presunie uzivatela spat na listing.
    */
    function deletePartner($id) {
        $partner = $this->wpdb->get_row('SELECT * FROM wp_partners WHERE id = '.$id);
        
        // vymazanie loga, aj suboru z disku
        wp_delete_attachment(get_post_meta($partner->post_id, 'logo', true));
        // vymazanie pridruzeneho postu
        wp_delete_post($partner->post_id);
        $this->wpdb->query('DELETE FROM wp_partners WHERE id = '.$id);
        
        // po uspesnom zmazni chod spat na listing
        unset($_GET['action']);
        unset($_GET['id']);        
        $this->listAll();
    }
    
    /**
    * @desc Listing partnerov.
    */
    function listing() {
        echo '<div id="wrap">';
        echo '<h2>Zoznam partnerov</h2>';
        $result = $this->wpdb->get_results("SELECT * FROM wp_partners");
        echo '<table class="form-table">';
        foreach ($result as $r) {
            echo '<tr><td><a href="?page=partnersMenu&action=edit&id='.$r->id.'">'.$r->name.'</a></td><td><a href="?page=partnersMenu&action=delete&id='.$r->id.'" onclick="return confirmDelete(\''.$r->name.'\')">Zmazať</a></td></tr>';
        }
        echo '</table>';
        echo '</div>';        
    }
    
    /**
    * @desc Vrati inicializaciu YUI editora.
    */
    private static function initYuiEditor() {
        $str = "<script type=\"text/javascript\">
                    var myEditor = new YAHOO.widget.Editor('partnerActivity', {
                        height: '200px',
                        width: '550px',
                        dompath: false,
                        animate: true,
                        toolbar: {
                            collapse: true,
                            titlebar: '',
                            draggable: false,
                            buttonType: 'advanced',
                            buttons: [
                                { group: 'fontstyle', label: 'Font Size',
                                    buttons: [
                                        { type: 'spin', label: '13', value: 'fontsize', range: [ 9, 75 ], disabled: true }
                                    ]
                                },
                                { type: 'separator' },
                                { group: 'textstyle', label: 'Font Style',
                                    buttons: [
                                        { type: 'push', label: 'Bold CTRL + SHIFT + B', value: 'bold' },
                                        { type: 'push', label: 'Italic CTRL + SHIFT + I', value: 'italic' },
                                        { type: 'push', label: 'Underline CTRL + SHIFT + U', value: 'underline' },
                                        { type: 'separator' },
                                        { type: 'push', label: 'Subscript', value: 'subscript', disabled: true },
                                        { type: 'push', label: 'Superscript', value: 'superscript', disabled: true },
                                        { type: 'separator' },
                                        { type: 'color', label: 'Font Color', value: 'forecolor', disabled: true },
                                        { type: 'color', label: 'Background Color', value: 'backcolor', disabled: true },
                                        { type: 'separator' },
                                        { type: 'push', label: 'Remove Formatting', value: 'removeformat', disabled: true },
                                        { type: 'push', label: 'Show/Hide Hidden Elements', value: 'hiddenelements' }
                                    ]
                                },
                                { type: 'separator' },
                                { group: 'alignment', label: 'Alignment',
                                    buttons: [
                                        { type: 'push', label: 'Align Left CTRL + SHIFT + [', value: 'justifyleft' },
                                        { type: 'push', label: 'Align Center CTRL + SHIFT + |', value: 'justifycenter' },
                                        { type: 'push', label: 'Align Right CTRL + SHIFT + ]', value: 'justifyright' },
                                        { type: 'push', label: 'Justify', value: 'justifyfull' }
                                    ]
                                },
                                { type: 'separator' },
                                { group: 'indentlist', label: 'Lists',
                                    buttons: [
                                        { type: 'push', label: 'Indent', value: 'indent', disabled: true },
                                        { type: 'push', label: 'Outdent', value: 'outdent', disabled: true },
                                        { type: 'push', label: 'Create an Unordered List', value: 'insertunorderedlist' },
                                        { type: 'push', label: 'Create an Ordered List', value: 'insertorderedlist' }
                                    ]
                                },
                                { type: 'separator' },
                                { group: 'insertitem', label: 'Insert Item',
                                    buttons: [
                                        { type: 'push', label: 'HTML Link CTRL + SHIFT + L', value: 'createlink', disabled: true }
                                    ]
                                }
                            ]

                        }
                    });

                    myEditor.render();
                    </script>";
        return $str;
    }
    
    /**
    * @desc Vrati zoznam partnerov.
    */
    function getPartners($cat1) {
        $projects = $this->wpdb->get_results('SELECT * FROM wp_partners WHERE category = '.$cat1);
        return $projects;
    }    
    
    /**
    * @desc Vrati partnera podla post_id.
    */
    function getPartnerByPostId($postId) {
        $project = $this->wpdb->get_row('SELECT * FROM wp_partners WHERE post_id = '.$postId);
        return $project;
    }
    
    /**
    * @desc Upravena funkcia pre upload suboru z functions.php.
    */
    private static function my_wp_upload_bits( $name, $deprecated, $bits, $time = null, $subFolder = '' ) {
        if ( empty( $name ) )
            return array( 'error' => __( 'Empty filename' ) );

        $wp_filetype = wp_check_filetype( $name );
        if ( !$wp_filetype['ext'] )
            return array( 'error' => __( 'Invalid file type' ) );

        $upload = wp_upload_dir( $time );

        if ( $upload['error'] !== false )
            return $upload;

        $filename = wp_unique_filename( $upload['path'], $name );

        $new_file = $upload['basedir'] . $subFolder . "/$filename";
        if ( ! wp_mkdir_p( dirname( $new_file ) ) ) {
            $message = sprintf( __( 'Unable to create directory %s. Is its parent directory writable by the server?' ), dirname( $new_file ) );
            return array( 'error' => $message );
        }

        $ifp = @ fopen( $new_file, 'wb' );
        if ( ! $ifp )
            return array( 'error' => sprintf( __( 'Could not write file %s' ), $new_file ) );

        @fwrite( $ifp, $bits );
        fclose( $ifp );
        // Set correct file permissions
        $stat = @ stat( dirname( $new_file ) );
        $perms = $stat['mode'] & 0007777;
        $perms = $perms & 0000666;
        @ chmod( $new_file, $perms );

        // Compute the URL
        $url = $upload['url'] . "/$filename";

        return array( 'file' => $new_file, 'url' => $url, 'error' => false );
    }
    
}

add_action('plugins_loaded', create_function('','global $vtpPartners; $vtpPartners = new VTPPartners();'));

?>